package com.dtguai.admin.util;


import com.dtguai.admin.common.error.ErrorCode;
import com.dtguai.admin.common.exception.DefinedException;
import com.dtguai.admin.web.sys.model.SysDefAdmin;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

/**
 * Shiro工具类
 *
 * @author guo
 */
public class ShiroUtils {

    private ShiroUtils() {
    }

    public static Session getSession() {
        return SecurityUtils.getSubject().getSession();
    }

    public static Subject getSubject() {
        return SecurityUtils.getSubject();
    }

    public static SysDefAdmin getAdmin() {
        return (SysDefAdmin) SecurityUtils.getSubject().getPrincipal();
    }

    public static Integer getUserId() {
        return getAdmin().getId();
    }

    public static void setSessionAttribute(Object key, Object value) {
        getSession().setAttribute(key, value);
    }

    public static Object getSessionAttribute(Object key) {
        return getSession().getAttribute(key);
    }

    public static boolean isLogin() {
        return SecurityUtils.getSubject().getPrincipal() != null;
    }

    public static String getKaptcha(String key) {
        Object kaptcha = getSessionAttribute(key);
        if (kaptcha == null) {
            throw new DefinedException(ErrorCode.VERIFICATION_CODE_LOSE_EFFICACY);
        }
        getSession().removeAttribute(key);
        return kaptcha.toString();
    }

}
